package com.ziyun.pop.mall.module.time.action;

import com.utility.StringUtils;
import com.ziyun.pop.mall.module.user.entity.PopUserAction;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 用户行为记录
 * 
 * @Author:chenxiaoyi
 * @Date:2018/11/6 8:57
 */
public class UserActionTake {

	private ConcurrentMap<String, PopUserAction> userActionMap;

	private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

	private UserActionTake() {
		userActionMap = new ConcurrentHashMap<>();
	}

	private static class InnerSingle {
		private static final UserActionTake instance = new UserActionTake();
	}

	public static UserActionTake getInstance() {
		return InnerSingle.instance;
	}

	/**
	 * 用户行为记入Map容器
	 *
	 */
	public void addUserTake(String url, String method) {
		if (StringUtils.isEmpty(url)) {
			return;
		}
		try {
			rwLock.readLock().lock();
			PopUserAction action = userActionMap.get(url);
			if (action == null) {
				PopUserAction popUserAction = PopUserAction.builder().url(url).method(method)
						.atomicLong(new AtomicLong(0L)).build();
				PopUserAction exist = userActionMap.putIfAbsent(url, popUserAction);
				action = exist == null ? popUserAction : exist;
			}
				action.getAtomicLong().incrementAndGet();

		} finally {
			rwLock.readLock().unlock();
		}
	}

	public ConcurrentMap<String, PopUserAction> getUserActionMap() {
		return this.userActionMap;
	}

	public ReentrantReadWriteLock getLock() {
		return this.rwLock;
	}
}
